package data;

import database.DataBaseConnection;
import org.owasp.esapi.Encoder;
import org.owasp.esapi.errors.EncodingException;
import org.owasp.esapi.reference.DefaultEncoder;

import java.sql.Blob;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class DownloadRecordData {
    private String id;
    private String column;

    public DownloadRecordData(String id, String column) {
        this.id = id;
        this.column = column;
    }

    public Blob downloadData(String tableName) {
        Blob result = null;
        Connection connection = DataBaseConnection.getConnection();
        if (connection != null) {
            String sql = "select " + column + " from " + tableName + " where id = " + id + "";
            ResultSet resultSet = DataBaseConnection.query(connection, sql);
            try {
                while (resultSet != null && resultSet.next()) {
                    result = resultSet.getBlob(column);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            DataBaseConnection.closeConnection(connection);
        }
        return result;
    }

    public String sanitize(String url) throws EncodingException {
        Encoder encoder = new DefaultEncoder(new ArrayList<>());
        String clean = encoder.canonicalize(url).trim();
        clean = encoder.decodeFromURL(clean);
        //detect and remove any existent \r\n == %0D%0A == CRLF to prevent HTTP Response Splitting
        int idxR = clean.indexOf('\r');
        int idxN = clean.indexOf('\n');
        if (idxN >= 0 || idxR >= 0) {
            if (idxN > idxR) {
                //just cut off the part after the LF
                clean = clean.substring(0, idxN - 1);
            } else {
                //just cut off the part after the CR
                clean = clean.substring(0, idxR - 1);
            }
        }
        //re-encode again
        return encoder.encodeForURL(clean);
    }
}
